/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveCreateInvitationFiles : CommandUtils.GrooveUtilBase
	{
		private string m_AccountURI;
		private string m_Role;
		private string m_NameFormat;
		
		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveCreateInvitationFiles(i_Arguments));
		}

		public GrooveCreateInvitationFiles(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveCreateInvitationFiles [PARAMS...]";
			base.HelpMessage = 
				"GrooveCreateInvitationFiles\r\n\t" + 
				"Creates invitation files to all Groove workspaces\r\n" +
				"Parameters:\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/Role=              \"Manager\", \"Member\" (default) or \"Guest\"\r\n\t" +
				"[/NameFormat=        Format for the filenames. Default \"{Role}_{SpaceName}\"\r\n\t" +
				"                         {SpaceName}: name of the workspace\r\n\t" +
				"                         {SpaceGUID}: GUID of the workspace\r\n\t" +
				"                         {Account}:   GUID of the Groove account\r\n\t" +
				"                         {Role}:      Role of invitee\r\n\t" +
				"                         {Date}:      current date, yyyymmdd\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;

			m_AccountURI = base.GetParameterValue( "Account" );

			m_NameFormat = base.GetParameterValue( "NameFormat" );
			if (System.String.IsNullOrEmpty(m_NameFormat))
				m_NameFormat = "{Role}_{SpaceName}";

			string Role = base.GetParameterValue("Role");
			if (!System.String.IsNullOrEmpty(Role))
			{
				if (Role.ToLower() == "manager")
					m_Role = "$Telespace.Manager";
				else if (Role.ToLower() == "member")
					m_Role = "$Telespace.Member";
				else if (Role.ToLower() == "guest")
					m_Role = "$Telespace.Guest";
				else
				{
					base.DisplayUsage("Invalid role specified.");
					return CommandUtils.UtilBase.CheckResult.Failed;
				}
			}
			else
				m_Role = "$Telespace.Member";

			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			GrooveWebServicesV12Helpers.Account[] Accounts = null;

			try
			{
				Accounts = GrooveWebServicesV12Helpers.Account.GetAccounts(base.Context);
			}
			catch (System.Exception ex)
			{
				base.StandardError.WriteLine("Unable to get list of accounts: " + ex.Message);
				throw ex;
			}

			foreach (GrooveWebServicesV12Helpers.Account Account in Accounts)
			{
				if (m_AccountURI!=null && m_AccountURI!=Account.URI)
				{
					// We have a specified account; this is not it
					continue;
				}
				foreach (GrooveWebServicesV12Helpers.Identity Identity in Account.Identities)
				{
					GrooveWebServicesV12Helpers.Space[] Spaces = null;
					try
					{
						Spaces = Identity.StandardSpaces;
					}
					catch (System.Exception Exception)
					{
						base.StandardError.WriteLine("Unable to get list of spaces: " + Exception.Message);
						throw Exception;
					}

					foreach (GrooveWebServicesV12Helpers.Space Space in Spaces)
					{
						if( Space.IsLocal )
						{
							try
							{
								System.Collections.Hashtable FormatTable = new System.Collections.Hashtable();
								FormatTable.Add("SpaceName", Space.Name);
								FormatTable.Add("SpaceType", Space.Type);
								FormatTable.Add("SpaceGUID", TelespaceGUID(Space) );
								FormatTable.Add("Role",      m_Role.Substring( m_Role.IndexOf(".")+1 ) );
								FormatTable.Add("Account",   Account.URI );
								FormatTable.Add("Date",      String.Format("{0:yyyyMMdd}",System.DateTime.Now) );
								FormatTable.Add("Time",      String.Format("{0:hhmmss}",System.DateTime.Now) );

								// Format the name
								string fileName = CommandUtils.UtilStatic.Format(m_NameFormat, FormatTable);

								foreach( char c in ":?*\'\"\\/|" )
								{
									fileName = fileName.Replace( c, '_' );
								}
								if( fileName=="" )
								{
									fileName = "untitled";
								}
								string invitationXML = Space.CreateInvitationFile( m_Role );
								System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName + ".grv");
								sw.Write( invitationXML );
								sw.Close();
							}
							catch (System.Exception e)
							{
								base.StandardError.WriteLine("Unable to create invitation: " + e.Message);
								throw e;
							}
						}
					}
				}
			}


			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}

		private string TelespaceGUID(GrooveWebServicesV12Helpers.Space i_Space)
		{
			string SpaceURI = i_Space.URI;
			int Index = SpaceURI.LastIndexOf("/");
			string TelespaceGUID = SpaceURI.Substring(Index + 1);
			
			return TelespaceGUID;
		}
	}

}
